<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="注意：运行为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
        >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row>
        <el-col class="cat_opt">
          <span>选择商品分类：</span>
          <!-- 商品分类级联选择器 -->
          <el-cascader
            :options="cateList"
            :props="cascaderProps"
            v-model="selectedCateKeys"
            @change="cateChanged"
            >
          </el-cascader>

        </el-col>
      </el-row>
      
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数</el-button>

          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag v-for="(val, index) in scope.row.attr_vals" :key="index" closable @close="removeAttrVals(index, scope.row)">{{ val }}
                </el-tag>
                <!-- 输入文本框 -->
                <!-- 为防止输入框共用同一数据，为el-input设置不同绑定值 scope.row.inputValue -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDailog(scope.row.attr_id)"></el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled"  @click="addDialogVisible=true">添加属性</el-button>

          <!-- 静态属性表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag v-for="(val, index) in scope.row.attr_vals" :key="index" closable @close="removeAttrVals(index, scope.row)">{{ val }}
                </el-tag>
                <!-- 输入文本框 -->
                <!-- 为防止输入框共用同一数据，为el-input设置不同绑定值 scope.row.inputValue -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDailog(scope.row.attr_id)"></el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
      >
      <!-- 添加参数对话框 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
      >
      <!-- 修改参数对话框 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectedCateKeys: [], // 选择分类id数据
      activeName: 'many',  // 被激活标签名称
      manyTabData: [],  // 动态参数数据
      onlyTabData: [],  // 静态属性数据
      addDialogVisible: false,  // 控制添加对话框显示隐藏
      addForm: {    // 添加表单对象
        attr_name: '',
      },
      addFormRules: {  // 添加表单验证规则
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },

      editDialogVisible: false,  // 控制修改对话框显示隐藏
      editForm: {    // 添加表单对象
        attr_name: '',
      },
      editFormRules: {  // 添加表单验证规则
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      inputVisible: false,  // 控制按钮与文本框切换显示，默认隐藏本文框
      inputValue: '',  // 文本框输入内容
    }
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const {data: res} = await this.$http.get('categories');
      if(res.meta.status != 200) return this.$message.error('获取商品分类失败');
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    cateChanged() {
      this.getParamsData();
    },
    handleTabClick() {  // 标签页点击事件
      // console.log(this.activeName);
      this.getParamsData();
    },
    async getParamsData() {
      // console.log(this.selectedCateKeys[this.selectedCateKeys.length - 1]);
      if(this.selectedCateKeys.length != 3) { // 选中的不是三级分类
        this.selectedCateKeys = [];

        // 将参数面板清除
        this.manyTabData = [];
        this.onlyTabData = [];

        return;
      }
      // 选中三级分类
      // console.log(this.selectedCateKeys);
      // 根据所选分类id和当前所处面板，获取对应参数
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: { sel: this.activeName } })
      if(res.meta.status != 200) return this.$message.error('获取参数失败');
      // console.log(res.data);
      res.data.forEach(item => {  // 循环并对attr_vals以空格分割
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []; // ''.split('') => [] 空字符串以空格分割返回[]，这里判断是否为空，为空则返回[]，防止循环空字符串  

        item.inputVisible = false;  // 控制文本框的显示与隐藏
        item.inputValue = ''; // 文本框中输入的值
      })
      // console.log(res.data);
      if(this.activeName === 'many') {  // 判断获取数据属于动态参数还是静态属性
        this.manyTabData = res.data;
      } else if(this.activeName === 'only') {
        this.onlyTabData = res.data;
      }
    },
    addDialogClosed() { // 监控对话框关闭事件
      this.$refs.addFormRef.resetFields();
    },
    addParams() { // 点击按钮，添加参数
      this.$refs.addFormRef.validate(async valid => {
        if(!valid) return;
        const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status != 201) return this.$message.error('添加参数失败');
        this.$message.success('添加参数成功');
        this.addDialogVisible = false;
        this.getParamsData();
      })
    },
    async showEditDailog(attr_id) {  // 点击按钮，显示修改对话框
      // 查询当前参数信息
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {paraqms: { attr_sel: this.activeName } });
      if(res.meta.status != 200) return this.$message.error('获取参数信息失败');
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    editDialogClosed() {  // 重置修改表单
      this.$refs.editFormRef.resetFields();
    },
    editParams() {  // 点击按钮，修改参数
      this.$refs.editFormRef.validate(async valid => {
        if(!valid) return;
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName });
        if(res.meta.status !== 200) return this.$message.error('修改参数失败');
        this.$message.success('修改参数成功');
        this.editDialogVisible = false;
        this.getParamsData();
      })
    },
    async removeParams(attr_id) {  // 点击按钮，根据id删除对应参数
      const confirmResult = await this.$confirm('此操作将删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);

      if(confirmResult != 'confirm') {
        return this.$message.info('取消删除操作');
      } else {
        const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`);
        if(res.meta.status != 200) return this.$message.error('删除参数失败');
        this.$message.success('删除参数成功');
        this.getParamsData();
      }
    },
    
    async handleInputConfirm(row) {  // 文本框失去焦点或按下enter键触发
      if(row.inputValue.trim().length === 0) {  // 当输入无内容或输入空格
        row.inputValue = '';
        row.inputVisible = false;
        return;
      }
      // 输入有内容
      row.attr_vals.push(row.inputValue.trim());  // 将输入内容追加到attr_vals数组
      row.inputValue = '';
      row.inputVisible = false;
      // 发起请求保存操作
      this.saveAttrVals(row);
    },
    // 将attr_vals的操作，保存数据库
    async saveAttrVals(row) {
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status != 200) return this.$message.error('添加参数失败');
      this.$message.success('添加参数成功')
    },
    showInput(row) { // 点击按钮，显示文本输入框
      row.inputVisible = true;
      this.$nextTick(_ => { // 文本框自动获取焦点，$nextTick方法作用：当页面元素重新渲染，才会执行回调函数中的代码
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    removeAttrVals(index, row) {  // 删除对应参数可选项
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    }
  },

  computed: {
    isBtnDisabled() { // 是否禁用按钮
      if(this.selectedCateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    cateId() {  // 选中的三级分类id
      if(this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null;
      }
    },
    titText() { // 动态计算标题的文本
      if(this.activeName === 'many') {
        return '动态参数';
      } else if(this.activeName === 'only') {
        return '静态属性';
      }
    }
  }

}
</script>
<style lang="less" scoped>
  .cat_opt{margin: 15px 0;}
  .el-tag{margin: 5px 10px;}
  .input-new-tag{width: 120px;}
</style>